package com.wenzhoujie.library.customview;

import android.view.View;
import android.view.View.OnClickListener;

public class SDViewNavigatorManager
{

	private SDViewBase[] mItems = null;
	private int mCurrentIndex = -1;
	private int mLastIndex = -1;
	private Mode mMode = Mode.MUST_ONE_SELECT;

	public int getmLastIndex()
	{
		return mLastIndex;
	}

	public Mode getmMode()
	{
		return mMode;
	}

	public void setmMode(Mode mMode)
	{
		this.mMode = mMode;
	}

	private SDViewNavigatorManagerListener mListener = null;

	public int getmCurrentIndex()
	{
		return mCurrentIndex;
	}

	public SDViewBase getSelectedView()
	{
		if (mItems != null && mCurrentIndex >= 0 && mCurrentIndex < mItems.length)
		{
			return mItems[mCurrentIndex];
		} else
		{
			return null;
		}
	}

	public SDViewNavigatorManagerListener getmListener()
	{
		return mListener;
	}

	public void setmListener(SDViewNavigatorManagerListener mListener)
	{
		this.mListener = mListener;
	}

	public void setItems(SDViewBase... items)
	{
		setItemsArr(items);
	}

	public void setItemsArr(SDViewBase[] items)
	{
		if (items != null && items.length > 0)
		{
			mItems = items;
			for (int i = 0; i < mItems.length; i++)
			{
				mItems[i].setId(i);
				mItems[i].setOnClickListener(new SDBottomNavigatorView_OnClickListener());
				mItems[i].onNormal();
			}
		}
	}

	class SDBottomNavigatorView_OnClickListener implements OnClickListener
	{

		@Override
		public void onClick(View v)
		{
			setSelectIndex(v.getId(), v, true);
		}

	}

	public boolean setSelectIndex(int index, View v, boolean notifyListener)
	{
		if (mItems != null && index >= 0 && index < mItems.length)
		{
			if (index != mCurrentIndex) // 如果点击的项不等于当前项
			{
				mItems[index].onSelected();
				if (mCurrentIndex >= 0)
				{
					mItems[mCurrentIndex].onNormal();
				}
				mLastIndex = mCurrentIndex;
				mCurrentIndex = index;
				if (mListener != null && notifyListener)
				{
					mListener.onItemClick(v, index);
				}
				return true;
			} else
			{
				switch (mMode)
				{
				case MUST_ONE_SELECT:

					break;
				case CAN_NONE_SELECT:
					if (mItems[index].ismSelected())
					{
						mItems[index].onNormal();
						mCurrentIndex = -1;
					} else
					{
						mItems[index].onSelected();
						mCurrentIndex = index;
					}
					break;

				default:
					break;
				}
			}
		}
		return false;
	}

	public boolean setSelectIndexLast(boolean notifyListener)
	{
		return setSelectIndex(mLastIndex, null, notifyListener);
	}

	public interface SDViewNavigatorManagerListener
	{
		public void onItemClick(View v, int index);
	}

	public enum Mode
	{
		MUST_ONE_SELECT, CAN_NONE_SELECT
	}
}
